package com.liang.liangapiinterface.controller;

import com.liang.liangclientsdk.utils.SignUtils;
import org.springframework.web.bind.annotation.*;
import com.liang.liangclientsdk.model.User;
import javax.servlet.http.HttpServletRequest;

/**
 * 名称Api
 *
 * @author Liang
 */
@RestController
@RequestMapping("/name")
public class NameController {
    @GetMapping("/get")
    public String getNameByGet(String name) {

        return "Get 的名字是" + name;
    }
    @PostMapping("/post")
    public String getNameByPost(@RequestParam String name) {
        return "Post 的名字是" + name;
    }
    @PostMapping("/user")
    public String getUserNameByPost(@RequestBody User user, HttpServletRequest request) {
        System.out.println("request");
        System.out.println(user);
        System.out.println(request);
        try {
            String accessKey = request.getHeader("accessKey");
            String nonce = request.getHeader("nonce");
            String timestamp = request.getHeader("timestamp");
            String sign = request.getHeader("sign");
            String body = request.getHeader("body");
            if(!accessKey.equals("liang")){
                throw new RuntimeException("无权限");
            }
            if(Long.parseLong(nonce) > 10000){
                throw new RuntimeException("nonce无权限");
            }

            long inputTimestamp = Long.parseLong(request.getHeader("timestamp"));
            long currentTime = System.currentTimeMillis() / 1000;
            long fiveMinutesAgo = currentTime - (5 * 60);
            if(inputTimestamp < fiveMinutesAgo){
                throw new RuntimeException("Timestamp无权限");
            }
            //根据accessKey从数据库查出secretKey
            String serverSign = SignUtils.genSign(body, "abcdefg");
            if(!sign.equals(serverSign)){
                throw new RuntimeException("secret无权限");
            }
            String result = "POST 用户名是" + user.getUsername();


        }catch(Exception e){
            return "发生错误：原因" + e;
        }
        // todo 实际情况去数据库查是否分配给用户

        return "Post 用户名是" + user.getUsername();
    }
}
